package com.wjh.kt_vod.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.wjh.kt_vod.model.vod.Chapter;
import com.wjh.kt_vod.model.vod.Video;
import com.wjh.kt_vod.service.ChapterService;
import com.wjh.kt_vod.mapper.ChapterMapper;
import com.wjh.kt_vod.service.VideoService;
import com.wjh.kt_vod.vo.vod.ChapterVo;
import com.wjh.kt_vod.vo.vod.VideoVo;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.LinkedList;
import java.util.List;

/**
 *
 */

@Service
public class ChapterServiceImpl extends ServiceImpl<ChapterMapper, Chapter>
        implements ChapterService {

    @Autowired
    private VideoService videoService;

    @Override
    public List<ChapterVo> getTreeList(Long courseId) {

//      根据课程id获取章节
        QueryWrapper<Chapter> chapterQueryWrapper = new QueryWrapper<>();
        chapterQueryWrapper.eq("course_id", courseId).orderByAsc("sort");
        List<Chapter> chapterList = baseMapper.selectList(chapterQueryWrapper);

//      根据章节id获取小结;
        LambdaQueryWrapper<Video> videoLambdaQueryWrapper = new LambdaQueryWrapper<>();
        videoLambdaQueryWrapper.eq(Video::getCourseId,courseId).orderByAsc(Video::getSort);
        List<Video> videoList = videoService.list(videoLambdaQueryWrapper);

        //封装数据集合
        LinkedList<ChapterVo> finalChapterList = new LinkedList<>();
        chapterList.stream().forEach(chapter -> {
            //封装章节
            ChapterVo chapterVo = new ChapterVo();
            BeanUtils.copyProperties(chapter,chapterVo);
            finalChapterList.add(chapterVo);

            //封装章节中的小结
            LinkedList<VideoVo> videoVoLinkedList = new LinkedList<>();
            videoList.stream().forEach(video -> {

                if (chapter.getId() == video.getChapterId()){
                    VideoVo videoVo = new VideoVo();
                    BeanUtils.copyProperties(video,videoVo);
                    videoVoLinkedList.add(videoVo);
                }
                chapterVo.setChildren(videoVoLinkedList);
            });

        });
        return finalChapterList;
    }

    /**
     * 根据课id删除章节
     * @param id
     */
    @Override
    public void removeChapterByCourseId(Long id) {

//        删除章节时删除小结

        LambdaQueryWrapper<Chapter> chapterLambdaQueryWrapper = new LambdaQueryWrapper<>();
        chapterLambdaQueryWrapper.eq(Chapter::getCourseId,id);
        baseMapper.delete(chapterLambdaQueryWrapper);
    }

    /**
     * 删除章节
     * @param id
     */
    @Override
    public void removeAndVideoAndVodById(Long id) {
        videoService.removeVideoByChapterId(id);
        baseMapper.deleteById(id);
    }


}




